package com.stone.common.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import net.sf.json.JSONArray;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.stone.utils.NumUtils;
import com.stone.utils.StringUtils;

/**
 *
 * @author jz
 * @since 2010-05-06
 */
public class AdvanceSearchJsonUtils {
    /** * logger. */
    private static Log logger = LogFactory.getLog(AdvanceSearchJsonUtils.class);


    protected AdvanceSearchJsonUtils() {
    }

    /**
     * 将高级查询的Json字符串转为List<Object>
     */
    public static HashMap<String,Object> jsonToList(String jsonString) throws Exception {
    	
    	HashMap<String,Object> map = new HashMap<String,Object> ();
		List<Object> valsList = new ArrayList<Object>();
		
		if (StringUtils.isNullOrBlank(jsonString)) {
	        map.put("conditions", "");
	        map.put("vals", valsList);
			return map;
		}

		JSONArray jarr=JSONArray.fromObject(jsonString);
        List<AdvanceSearchJsonBean> listJson  = (List<AdvanceSearchJsonBean>)jarr.toCollection(jarr,AdvanceSearchJsonBean.class);
        String conditions = " AND (";
        
        for (AdvanceSearchJsonBean bean : listJson) {
        	
        	conditions += bean.getConditon();
        	
        	if ("Long".equals(bean.getType())) {
        		valsList.add(NumUtils.parseLong(bean.getVal()));
        	} else if ("Integer".equals(bean.getType())) {
        		valsList.add(NumUtils.parseInt(bean.getVal()));
        	} else if ("Double".equals(bean.getType())) {
        		valsList.add(NumUtils.parseDouble(bean.getVal()));	
        	}  else if ("Float".equals(bean.getType())) {
        		valsList.add(NumUtils.parseFloat(bean.getVal()));	
        	} else {
        		valsList.add( bean.getVal().toString());
        	}
        	
        }
        
        conditions += " )";
        map.put("conditions", conditions);
        map.put("vals", valsList);
        
        return map;
    }
}
